package com.hb.bussiness.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

@Configuration
@ConfigurationProperties(prefix = "spring.redis")
public class RedisTokenStoreConfig {

	private final static Logger logger = LoggerFactory.getLogger(RedisTokenStoreConfig.class);

	private String host;

	private int port;

	private String password;
	private int database;

	@Bean
	public RedisMessageListenerContainer container(
			@Qualifier("tokenRedisFactory") RedisConnectionFactory connectionFactory) {

		RedisMessageListenerContainer container = new RedisMessageListenerContainer();
		container.setConnectionFactory(connectionFactory);
		return container;
	}

	@Bean
	public TokenStore getTokenStore(@Qualifier("tokenRedisFactory") LettuceConnectionFactory connectionFactory) {

		RedisTokenStore redisTokenStore = new RedisTokenStore(connectionFactory);
		return redisTokenStore;
	}

	@Bean("tokenRedisFactory")
	public LettuceConnectionFactory createRedisConnectionFactory() {
		logger.info("create redis token store in host:{},port:{},password:{}", host, port, password);
		return this.connectionFactory(host, port, password, 20, 1024, 100000, 0);
	}

	public LettuceConnectionFactory connectionFactory(String host, int port, String password, int maxIdle, int maxTotal,
                                                      long maxWaitMillis, int index) {
		RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();
		config.setHostName(host);
		config.setPort(port);
		config.setDatabase(database);
		config.setPassword(password);

		return new LettuceConnectionFactory(config);
	}

	public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public int getDatabase() {
		return database;
	}

	public void setDatabase(int database) {
		this.database = database;
	}
}

